package com.eric.springboot.utils;

import com.eric.springboot.common.ResultCode;
import com.eric.springboot.config.security.JwtUserDetails;
import com.eric.springboot.exception.BaseException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author codermy
 * @createTime 2020/8/4
 */
public class SecurityUtils {

    /**
     * 获取当前用户名称
     *
     * @return 当前用户名称
     */
    public static String getCurrentUserName() {
        return getCurrentUser().getUsername();
    }

    /**
     * 获取当前用户id
     *
     * @return 当前用户id
     */
    public static Long getCurrentUserId() {
        return getCurrentUser().getId();
    }

    /**
     * 获取当前用户
     *
     * @return 当前用户
     */
    public static JwtUserDetails getCurrentUser() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || "anonymousUser".equals(authentication.getPrincipal().toString())) {
            throw new BaseException(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage());
        }
        return (JwtUserDetails) authentication.getPrincipal();
    }

}


